#!/usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      qs = require('querystring');
http.createServer((req, res) => {
  //log(`${req.method} ${req.url} HTTP/${req.httpVersion}`)

  //log(req.headers)

  //log()
  
  if (req.url === '/') {
    if (req.method === 'GET') {
      // return html
      let html = fs.readFileSync('./04-form-server.html').toString('utf8')
      res.end(html)

    } else if (req.method === 'POST') {

        let data = ''
        req.on('data', (chunk) => {
          data += chunk
        })
        req.on('end', () => {
          console.log(qs.parse(data))
          res.end('ok')
        })
    } else {
        err(req, res)
    } 
  } else {
    err(req, res)
  }
}).listen(3000)

function err(req, res){
  res.statusCode = 404
  res.end(`${req.url} Not Found`)
}

